$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange }) {
    var mstform = $NG.getCmpApi("p_form_Milestone_Plan_m"); //里程碑计划主表
    var dgrid1 = $NG.getCmpApi("p_form_Milestone_Plan_d"); //里程碑计划明细
    var dgrid2 = $NG.getCmpApi("p_form_Milestone_Task_d"); //里程碑任务明细
    var dgrid3 = $NG.getCmpApi("p_form_Milestone_Repay_d"); //里程碑回款明细
    var dgrid4 = $NG.getCmpApi("p_form_Construction_plan"); //施工计划
    var dgrid5 = $NG.getCmpApi("p_form_Income_Plan"); //收入计划
    var dgrid6 = $NG.getCmpApi("p_form_Unconverted_Income"); //未转化收入分析
  
    var dtoolbar1 = $NG.getCmpApi("toolbar_p_form_Milestone_Plan_d");
    var dtoolbar2 = $NG.getCmpApi("toolbar_p_form_Milestone_Task_d");
    var dtoolbar3 = $NG.getCmpApi("toolbar_p_form_Milestone_Repay_d");
  
    ////////////////////////////////////////////////////////////--toolbar--////////////////////////////////////////////////////////////
    dtoolbar1.hideButton("addrow");
    dtoolbar1.hideButton("attachment");
    dtoolbar2.hideButton("addrow");
    dtoolbar2.hideButton("attachment");
    dtoolbar3.hideButton("addrow");
    dtoolbar3.hideButton("deleterow");
    dtoolbar3.hideButton("attachment");
    dtoolbar1.insert({
      id: "addMilestone",
      text: "新增里程碑",
      iconCls: "icon-New",
    });
    dtoolbar2.insert({
      id: "addMilestoneTask",
      text: "新增里程碑任务",
      iconCls: "icon-New",
    });
    dtoolbar2.insert({
      id: "addRepayTask",
      text: "新增回款任务",
      iconCls: "icon-New",
    });
    ////////////////////////////////////////////////////////////--useClick--////////////////////////////////////////////////////////////
    useClick(async function ({ args }) {
      addMilestone();
    }, "addMilestone");
    useClick(async function ({ args }) {
      addMilestoneTaskClick();
    }, "addMilestoneTask");
    useClick(async function ({ args }) {
      addRepayTask();
    }, "addRepayTask");
    useClick(async function ({ args }) {
      setTimeout(function () {
        updateRepay();
      }, 500);
    }, "deleterow");
  
    //按钮单击事件
    // dtoolbar3.getItem("deteterow").getRef().click();
  
    ////////////////////////////////////////////////////////////--init--////////////////////////////////////////////////////////////
    dgrid6UpdateUI();
    if (mstform.getItem("phid_pc").getValue()) {
      getPtInfoByPhid();
      dgrid4Filter();
    }
    if (page.oType == "add") {
      dgrid6AddRows();
    }
    if (page.oType == "add" || page.oType == "copy") {
      addRepayPlan();
    }
  
    ////////////////////////////////////////////////////////////--useValuesChange--////////////////////////////////////////////////////////////
    useValuesChange(({ args }) => {
      getPtInfoByPhid();
      addRepayPlan();
      dgrid4Filter();
    }, "p_form_Milestone_Plan_m.phid_pc");
    useValuesChange(({ args }) => {
      dgrid6UpdateUI();
    }, "p_form_Milestone_Plan_m.u_report_dt");
    ////////////////////////////////////////////////////////////--useDataIndexChange--////////////////////////////////////////////////////////////
    useDataIndexChange(({ args, instance }) => {
      updateRepay();
    }, "p_form_Milestone_Plan_d.u_plan_start_dt");
    useDataIndexChange(({ args, instance }) => {
      updateRepay();
    }, "p_form_Milestone_Plan_d.u_plan_end_dt");
    useDataIndexChange(({ args, instance }) => {
      updateRepay();
    }, "p_form_Milestone_Task_d.u_intervaltime");
    //根据工作单元ID获取工作单元清单
    useDataIndexChange(({ args, instance }) => {
      $NG.execServer("getGzdyqdByPhid", { phid: args[0].u_gzdy_name }, function (res) {
        if (res.count > 0) {
          data = JSON.parse(res.data)[0].extendObjects;
          args[0].u_gzdy_no = data.u_gzdy_code;
          args[0].u_sggx_on = data.process_no;
          args[0].u_sggx_name = data.process_id;
          args[0].u_sggx_name_EXName = data.process_name;
          instance.updateRow(args[0]);
        } else {
          console.log("功能扩展暂无数据");
        }
      });
    }, "p_form_Construction_plan.u_gzdy_name");
    ////////////////////////////////////////////////////////////--useUpdateRows--////////////////////////////////////////////////////////////
    useUpdateRows(({ args }) => {
      const fields = [
        "u_current_month",
        "u_current_month_add1",
        "u_current_month_add2",
        "u_current_month_add3",
        "u_year_addmonth01",
        "u_year_addmonth02",
        "u_year_addmonth03",
        "u_year_addmonth04",
        "u_year_addmonth05",
        "u_year_addmonth06",
        "u_year_addmonth07",
        "u_year_addmonth08",
        "u_year_addmonth09",
        "u_year_addmonth10",
        "u_year_addmonth11",
        "u_year_addmonth12",
        "u_no_to_amt",
      ];
      let fieldSums = {};
      fields.forEach((field) => {
        fieldSums[field] = 0;
      });
  
      args[0].forEach((item) => {
        if (parseInt(item.u_no_to_type) <= 7) {
          fields.forEach((field) => {
            fieldSums[field] += parseFloat(item[field]) || 0;
          });
        }
      });
      //合计前置数据到合计行
      args[0].forEach((item) => {
        if (item.u_no_to_type === "91") {
          fields.forEach((field) => {
            item[field] = fieldSums[field]; // Set the field to its cumulative sum
          });
        }
  
        // 合计每一行的数据到合计列
        let rowSum = 0;
        fields.forEach((field) => {
          rowSum += parseFloat(item[field]) || 0;
        });
        item.u_amt = rowSum;
      });
  
      dgrid6.refreshView();
    }, "p_form_Unconverted_Income");
    let timeId= 0
    useUpdateRows(({ args }) => {
        if(page.oType =='add'||page.oType =='edit')
		if (timeId != 0) {
            clearTimeout(timeId)
            timeId=0
        };
		timeId = setTimeout(() => {
            console.log(`监听`);
			try {
				const _arr = args[0];
				const currentCheck = dgrid1.getSelectedData()[0];
				const dateC = calculateDateDifference(
					currentCheck.u_plan_end_dt,
					currentCheck.u_plan_start_dt
				);
				console.log(dateC);
				_arr.forEach((item) => {
					switch (item.u_standardtype) {
						case "2":
							item.u_plan_start_dt = addDaysToDate(
								currentCheck.u_act_end_dt,
								Number(item.u_intervaltime) || 0
							);
							break;
						case "3":
							item.u_plan_start_dt = addDaysToDate(
								currentCheck.u_plan_start_dt,
								Number(item.u_intervaltime) || 0
							);
							break;
						case "4":
							item.u_plan_start_dt = addDaysToDate(
								currentCheck.u_plan_end_dt,
								Number(item.u_intervaltime) || 0
							);
							break;
					}
					item.u_plan_end_dt = addDaysToDate(
						item.u_plan_start_dt,
						Number(dateC) || 0
					);
				});
			} catch (err) {}finally{
		dgrid2.refreshView();
                timeId = 0
            }
		}, 500);
	}, "p_form_Milestone_Task_d");
  
    ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
    function dgrid6UpdateUI(params) {
      $NG.updateUI((updater) => {
        let currentDate = new Date(mstform.getValues().u_report_dt || new Date());
        let dateFields = [];
        for (let i = 0; i < 16; i++) {
          year = currentDate.getFullYear();
          month = currentDate.getMonth() + 1; // getMonth() 返回 0-11，所以加 1
          let field = `${year}年${month}月`;
          dateFields.push(field);
          currentDate.setMonth(currentDate.getMonth() + 1);
        }
        const fields = [
          "u_current_month",
          "u_current_month_add1",
          "u_current_month_add2",
          "u_current_month_add3",
          "u_year_addmonth01",
          "u_year_addmonth02",
          "u_year_addmonth03",
          "u_year_addmonth04",
          "u_year_addmonth05",
          "u_year_addmonth06",
          "u_year_addmonth07",
          "u_year_addmonth08",
          "u_year_addmonth09",
          "u_year_addmonth10",
          "u_year_addmonth11",
          "u_year_addmonth12",
        ];
        fields.forEach((field, index) => {
          updater.editGrid.p_form_Unconverted_Income[field].setProps({
            header: dateFields[index],
          });
        });
      });
    }
    function dgrid6AddRows(params) {
      dgrid6.addRows([{ u_no_to_type: "1" }, { u_no_to_type: "2" }, { u_no_to_type: "3" }, { u_no_to_type: "4" }, { u_no_to_type: "5" }, { u_no_to_type: "6" }, { u_no_to_type: "7" }, { u_no_to_type: "91" }, { u_no_to_type: "92" }, { u_no_to_type: "93" }, { u_no_to_type: "94" }]);
    }
  
    function dgrid4Filter() {
      $NG.updateUI((updater) =>
        updater.editGrid.p_form_Construction_plan.u_gzdy_name.setProps((p) => {
          return {
            ...p,
            editor: {
              ...p.editor,
              clientSqlFilter: `m.phid_pc='${mstform.getItem("phid_pc").getValue() || 0}'`,
            },
          };
        })
      );
    }
  
    function getPtInfoByPhid() {
      if (mstform.getItem("phid_pc").getValue()) {
        $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
          const datas = JSON.parse(res.data)[0].extendObjects;
          console.log("getPtInfoByPhid:");
          console.log(datas);
          $NG.updateState((updater) => {
            updater.data.p_form_Milestone_Plan_m.setProps({
              //项目类型
              u_wbs_type: { value: datas.type_phid, label: datas.type_name },
            });
          });
        });
      }
    }
    function filter_help(table, key, d = "rel_key1") {
      //遍历表格
      let str = "";
      const _arr = table.getRows();
      console.log(_arr);
      const _is = [];
      _arr.forEach((item) => {
        _is.push(String(item[d]));
      });
      if (_is.length == 0) {
      } else {
        str = `and ${key} not in (`;
        _is.forEach((item, index) => {
          if (index > 0) {
            str += `,'${item}'`;
          } else {
            str += `'${item}'`;
          }
        });
        str += ")";
      }
      console.log(str);
      return str;
    }
    function addMilestone() {
      if (!mstform.getItem("u_wbs_type").getValue()) {
        $NG.alert("请先选择项目类型");
        return;
      }
  
      $NG.external
        .openNGHelp({
          type: "NGMultipleHelp",
          helpId: "view_Task_Templates_d",
          valueField: "phid",
          labelField: "u_milestone_name",
          clientSqlFilter: `u_wbs_type= ${mstform.getItem("u_wbs_type").getValue()} ${filter_help(dgrid1, "phid")}`,
        })
        .then((data) => {
          try {
            if (Array.isArray(data) && data.length > 0) {
              var gridArr = [];
              for (var i = 0; i < data.length; i++) {
                var gridObj = {};
                gridObj.rel_key1 = data[i].origin.phid;
                gridObj.u_phase = data[i].origin.u_phase || "";
                gridObj.u_milestone_no = data[i].origin.u_milestone_no || "";
                gridObj.u_milestone_name = data[i].origin.u_milestone_name || "";
                gridObj.u_milestone_type = data[i].origin.u_milestone_type_id;
                gridObj.u_milestone_type_EXName = data[i].origin.u_milestone_type_name || "";
                gridObj.u_start_dt = data[i].origin.u_start_dt || "";
                gridObj.u_end_dt = data[i].origin.u_end_dt || "";
                gridArr.push(gridObj);
              }
              console.log("addMilestone gridArr:");
              console.log(gridArr);
              dgrid1.addRows(gridArr);
              dgrid1.refreshView();
            } else {
              console.error("返回的数据无效或为空:", data);
            }
          } catch (error) {
            console.error("处理数据时出错:", error);
          }
        })
        .catch((error) => {
          console.error("打开NGHelp时发生错误:", error);
        });
    }
    function addMilestoneTaskClick() {
      if (!dgrid1.getSelectedData()[0]) {
        $NG.alert("请先选择对应的里程碑");
        return;
      }
      // console.log("u_wbs_type" + mstform.getItem("u_wbs_type").getValue());
      // console.log("u_milestone_no" + dgrid1.getSelectedData()[0].u_milestone_no);
      $NG.external
        .openNGHelp({
          type: "NGMultipleHelp",
          helpId: "Task_Templates_dd",
          valueField: "dd.phid",
          labelField: "dd.deliverables",
          clientSqlFilter: "d.u_wbs_type = " + mstform.getItem("u_wbs_type").getValue() + " and d.u_milestone_no='" + dgrid1.getSelectedData()[0].u_milestone_no + "'" + filter_help(dgrid2, "dd.u_deliverables", "u_deliverables"),
        })
        .then((data) => {
          try {
            // console.log(data);
            if (Array.isArray(data) && data.length > 0) {
              var gridArr = [];
              // console.log(data.length);
              for (var i = 0; i < data.length; i++) {
                var gridObj = {};
                gridObj.rel_key1 = dgrid1.getSelectedData()[0].rel_key1;
                gridObj.u_plan_start_dt = dgrid1.getSelectedData()[0].u_plan_start_dt;
                gridObj.u_plan_end_dt = dgrid1.getSelectedData()[0].u_plan_end_dt;
                gridObj.u_deliverables = data[i].origin.u_deliverables;
                gridObj.u_deliverable_type = data[i].origin.u_deliverable_type;
                gridObj.u_busid = data[i].origin.u_busid;
                gridObj.u_busid_EXName = data[i].origin.busname || "";
                gridObj.u_standardtype = data[i].origin.u_standardtype;
                gridObj.u_intervaltime = data[i].origin.u_intervaltime;
                gridObj.u_isneed = data[i].origin.u_isneed;
                gridObj.u_donepoint = data[i].origin.u_donepoint;
                gridObj.u_sendmsg = data[i].origin.u_sendmsg;
                gridArr.push(gridObj);
              }
              console.log("addMilestoneTask gridArr:");
              console.log(gridArr);
              dgrid2.addRows(gridArr);
              dgrid2.refreshView();
            } else {
              console.error("返回的数据无效或为空:", data);
            }
          } catch (error) {
            console.error("处理数据时出错:", error);
          }
        })
        .catch((error) => {
          console.error("打开NGHelp时发生错误:", error);
        });
    }
    function addRepayTask() {
      if (!dgrid1.getSelectedData()[0]) {
        $NG.alert("请先选择对应的里程碑");
        return;
      }
  
      $NG.external
        .openNGHelp({
          type: "NGMultipleHelp",
          helpId: "p_form_payment_plan_d",
          valueField: "d.phid",
          labelField: "d.u_hklcb",
          clientSqlFilter: "m.phid_pc = " + mstform.getItem("phid_pc").getValue() + filter_help(dgrid2, "d.u_hklcb", "u_fund_name"),
        })
        .then((data) => {
          try {
            // console.log(data);
            if (Array.isArray(data) && data.length > 0) {
              var gridArr = [];
              // console.log(data.length);
              for (var i = 0; i < data.length; i++) {
                var gridObj = {};
                gridObj.rel_key1 = dgrid1.getSelectedData()[0].rel_key1;
                gridObj.u_plan_start_dt = dgrid1.getSelectedData()[0].u_plan_start_dt;
                gridObj.u_plan_end_dt = dgrid1.getSelectedData()[0].u_plan_end_dt;
                gridObj.u_deliverables = "回款任务";
                gridObj.u_deliverable_type = "1";
                gridObj.u_busid = 77;
                gridObj.u_busid_EXName = "承包合同收款";
                gridObj.u_standardtype = "4";
                gridObj.u_intervaltime = "";
                gridObj.u_isneed = "2";
                gridObj.u_donepoint = "2";
                gridObj.u_sendmsg = "1";
                gridObj.u_fund_name = data[i].origin.u_hklcb;
                gridObj.amt = data[i].origin.u_hk_amt;
                gridArr.push(gridObj);
              }
              console.log("addRepayTask gridArr:");
              console.log(gridArr);
              dgrid2.addRows(gridArr);
              dgrid2.refreshView();
            } else {
              console.error("返回的数据无效或为空:", data);
            }
          } catch (error) {
            console.error("处理数据时出错:", error);
          }
        })
        .then(() => {
          try {
            setTimeout(function () {
              updateRepay();
            }, 500);
          } catch (error) {
            console.error("调用 updateRepay 时发生错误:", error);
          }
        })
        .catch((error) => {
          console.error("打开NGHelp时发生错误:", error);
        });
    }
    function addRepayPlan() {
      if (dgrid3 && mstform.getItem("phid_pc").getValue()) {
        dgrid3.clearRows();
        $NG.execServer("getPaymentPlanByPhid_pc", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
          if (res.count == 0) return;
          const data = JSON.parse(res.data);
          console.log("getPaymentPlanByPhid_pc");
          console.log(res.data);
          var gridArr = [];
          var gridCount = res.count;
          for (var i = 0; i < gridCount; i++) {
            var gridObj = {};
            //对表体字段进行赋值,可以取数据库中的值进行赋值
            gridObj.u_fund_name = data[i].extendObjects.u_hklcb;
            gridObj.amt = data[i].extendObjects.u_hk_amt;
            gridObj.u_hkzq = data[i].extendObjects.u_hkzq;
            // gridObj.u_plan_dt = data[i].extendObjects.u_total_daily_amt;
            gridArr.push(gridObj);
          }
          //调用新增表体行数据的函数
          dgrid3.addRows(gridArr);
        });
      }
    }
    function updateRepay(params) {
      var selectedData = dgrid1.getSelectedData()[0] || {};
      var rel_key1 = selectedData.rel_key1 || "";
      var u_phase = selectedData.u_phase || "";
      var u_milestone_no = selectedData.u_milestone_no || "";
      var u_milestone_name = selectedData.u_milestone_name || "";
      var u_plan_start_dt = selectedData.u_plan_start_dt || "";
      var u_plan_end_dt = selectedData.u_plan_end_dt || "";
  
      // 用于存储 dgrid2 中符合条件的 u_fund_name
      var fundNames = [];
      // 遍历 dgrid2，找到 rel_key1 相等的行并记录 u_fund_name
      dgrid2.getRows().forEach(function (item) {
        // item.u_plan_end_dt = u_plan_end_dt;
        let newDate = null;
        if (u_plan_start_dt) {
          newDate = new Date(u_plan_start_dt);
          newDate.setDate(newDate.getDate() + item.u_intervaltime); // 加上 u_hkzq 天数
          item.u_plan_start_dt = formatDate(newDate, "yyyy-mm-dd"); // 更新 u_plan_dt
        } else {
          item.u_plan_start_dt = null;
        }
        if (item.rel_key1 === rel_key1) {
          fundNames.push(item.u_fund_name);
        }
      });
      console.log("fundNames:");
      console.log(fundNames);
      // 遍历 dgrid3，更新符合条件的行的 u_plan_dt
      dgrid3.getRows().forEach(function (item) {
        if (fundNames.includes(item.u_fund_name)) {
          item.u_phase = u_phase;
          item.u_milestone_no = u_milestone_no;
          item.u_milestone_name = u_milestone_name;
          item.u_plan_end_dt = u_plan_end_dt;
          // 计算新的 u_plan_dt
          let newDate = null;
          if (u_plan_end_dt) {
            newDate = new Date(u_plan_end_dt);
            if (!isNaN(newDate)) {
              newDate.setDate(newDate.getDate() + item.u_hkzq); // 加上 u_hkzq 天数
              item.u_plan_dt = formatDate(newDate, "yyyy-mm-dd"); // 更新 u_plan_dt
            } else {
              console.error("Invalid date format for u_plan_end_dt:", u_plan_end_dt);
              item.u_plan_dt = null;
            }
          } else {
            item.u_plan_dt = null;
          }
        } else {
          // item.u_phase = "";
          // item.u_milestone_no = "";
          // item.u_milestone_name = "";
          // item.u_plan_end_dt = "";
        }
      });
      dgrid2.refreshView();
      dgrid3.refreshView();
    }
    // 日期格式化
    function formatDate(dateStr, outputFormat) {
      const date = new Date(dateStr);
  
      if (isNaN(date)) {
        return "无效的日期字符串";
      }
  
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
  
      let formattedDate;
  
      switch (outputFormat) {
        case "yyyy-mm-dd":
          formattedDate = `${year}-${month}-${day}`;
          break;
        case "yyyy-mm-dd HH:mm":
          formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
          break;
        // 可以根据需要继续添加其他格式的处理逻辑
        case "YYYYmmDD":
          formattedDate = `${year}${month.padStart(2, "0")}${day.padStart(2, "0")}`;
          break;
        default:
          formattedDate = "不支持的输出格式";
      }
  
      return formattedDate;
    }
    // 表体插入重复数据的检测方法
    function insertIfNotExists(data) {
      // 获取当前表体的所有行
      const existingRows = $NG.getCmpApi("p_form_Milestone_Task_d").getRows();
      // 创建一个Map来快速查找u_htzjxx
      const existingRowsMap = new Map(existingRows.map((row) => [row.u_htzjxx, true]));
  
      // 收集需要插入的新行（这里假设我们直接插入整个data对象，但您可能只需要部分）
      const newRows = [];
  
      data.forEach((item) => {
        // 检查该item的origin.phid是否已在existingRows中
        if (!existingRowsMap.has(item.origin.phid)) {
          // 如果不存在，则添加到newRows中（这里以整个item为例）
          newRows.push(item);
  
          // 注意：如果您只想插入部分数据，请在这里进行修改
          // 例如：newRows.push({ /* 仅包含您想插入的字段 */ });
        }
        // 如果存在，则不执行任何操作，因为不需要插入
      });
  
      // 现在，newRows包含了所有需要插入的行
      // 接下来，您可能需要调用另一个API或函数来实际执行插入操作
      // 假设有一个函数叫做 insertRows，它接受一个数组并插入到表体中
      // insertRows(newRows); // 这需要您自己实现或调用现有的API
  
      // 注意：这里我没有实现insertRows函数，因为它将依赖于您的具体API或框架
      console.log("需要插入的数组对象:", newRows); // 仅用于演示
      return newRows;
    }
    function addDaysToDate(dateString, daysToAdd) {
        if(!dateString) return ""
        // 将日期字符串转换为 Date 对象
        let date = new Date(dateString);
        
        // 增加天数
        date.setDate(date.getDate() + daysToAdd);
        
        // 获取新的日期并格式化成 YYYY-MM-DD 格式
        let year = date.getFullYear();
        let month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以加1
        let day = date.getDate().toString().padStart(2, '0');
      
        return `${year}-${month}-${day}`;
      }
      function calculateDateDifference(date1, date2) {
        if(!date1||!date2) return ""
        // 将日期字符串转换为 Date 对象
        let d1 = new Date(date1);
        let d2 = new Date(date2);
      
        // 计算两个日期的差值（以毫秒为单位）
        let timeDifference = Math.abs(d2 - d1);
        
        // 转换为天数
        let dayDifference = timeDifference / (1000 * 3600 * 24);
      
        return dayDifference;
      }
      
      // 示例调用
      
      
  });
  